#!/bin/bash -e

function info() {
echo Usage: `basename $0` in.files
exit 65
}

while getopts  ":s:t:h" opts
do
	case  $opts  in
	s) sample_name=$OPTARG;;
	t) type=$OPTARG;;
	h) info;;
	\?)
		
		echo `basename $0`': invalid option'
		exit 1
		;;
	esac
done
shift $(($OPTIND - 1))

if [ -z "$1" ]; then info; fi



if [ -z "$type" ]; then
	type=zip;
	dest_sub=.zip
elif test "$type" = "cnv"; then
	dest_sub=.cnvsc
elif test "$type" = "snp"; then
	dest_sub=.snp
elif test "$type" = "tes"; then
	dest_sub=.tes
elif test "$type" = "info"; then
	dest_sub=.info
elif test "$type" = "test"; then
	dest_sub=.test
else
	if
	echo $type |grep -P '^(snp|cnv|info|tes|test)\/'
	then
	dest_sub=.$type
	else
	echo `basename $0` type wrong.
	exit 65
	fi
fi


. /mnt/ilustre/app/medical/tools/.var


dir0=$(pwd |awk -F'/' '{print $NF}')
# dir=$dest/$dest_sub/$dir0
dir=$dest/$dest_sub
echo destination: $dir

if test ! -d $dir; then
mkdir -p $dir
# chmod 775 $dir
fi

for fil; do
if test -e $fil; then
fils="$fils $fil"
fi
done

echo $fils

# cp -r --backup=numbered --preserve=timestamps -t $dir $@

dir_base=`basename $PWD`

files=`junct_dir_file.pl ${dir_base} $fils`

cd ..

zip $dir/$dir_base.zip $files

# for file in $(ls -A $dir); do
# if test -d $file; then
# chmod -R 770 $dir/$file
# else
# chmod 660 $dir/$file
# fi
# done

# list=$dest/$dest_sub/.list
list=$dir/.list

if test -e $list; then
	cut -f1 $list >list1
	dir1=^$dir0$
	if grep $dir1 list1; then
		rm list1
	else
		rm list1
		echo -e $dir0'\t'`date -r $( ls -1t |sed -n '1p') +%s`'\t'`pwd` >> $dest/$dest_sub/.list
	fi
	
else
	echo -e $dir0'\t'`date -r $( ls -1t |sed -n '1p') +%s`'\t'`pwd` >> $dest/$dest_sub/.list
fi

# cd $dest/$dest_sub
# cat $dest/$dest_sub/.list |sort -r -k2 |format_html_index.pl -n$type |cat $tools_path/html/header.html - $tools_path/html/footer.html > $dest/$dest_sub/index.html